/******************** 
	作用:新增门店
	作者:蔡俊雄
	版本:V1.0
	时间:2015-08-22
********************/

$(function() {
	var levelTip1 = $("#category1").attr("data-tip"); //一级分类提示
	var levelTip2 = $("#category2").attr("data-tip"); //二级分类提示
	var levelTip3 = $("#category3").attr("data-tip"); //三级分类提示
	var idNotSelect = "0"; //不选分类时的ID


	General.extendDialog(); //扩展对话框

//	$('#storeTab a:first').tab('show');
	//	$('#storeTab a:eq(3)').tab('show');
	//-----------------上传图片设置-----------------
	//编辑器设置
	var uploadEditor = KindEditor.editor({
		uploadJson: '/shop/admin/store/StoreList?isUpfile=1',
		//uploadJson: '/file/upload',
		//fileManagerJson: '/file/list',
		allowFileManager: true
	});
	//显示图片上传对话框
	function showImageUploadDialog(imageId, hiddenId) {
		uploadEditor.loadPlugin('image', function() {
			uploadEditor.plugin.imageDialog({
				showRemote:false,
				imageUrl: $(hiddenId).val(),
				clickFn: function(url, title, width, height, border, align) {
					$(hiddenId).val(url);
					$(imageId).attr("src", url);
					uploadEditor.hideDialog();
				}
			});
		});
	}

	function initImageUploadDialog(btnId, imageId, hiddenId) {
		$(btnId).on("click", function(e) {
			showImageUploadDialog(imageId, hiddenId);
		});
	}

	$("#logo").blur(function() {
		var url = $("#logo").val();
		if (url)
			$("#previewImage").attr("src", url);
	});

	initImageUploadDialog("#upload,#previewImage", "#previewImage", "#logo");


	//-----------------省市区关联操作-----------------
	initCategory();
	//初始化一级分类
	function initCategory() {
		//获取数据
		try {
			//			categoryData=JSON.parse($("#categoryData").val());
			categoryData = eval($("#categoryData").val());
		} catch (e) {
			categoryData = [];
		}

		var str = '';
		str += '<option value="' + idNotSelect + '" selected>' + levelTip1 + '</option>';
		$.each(categoryData, function(index, obj) {
			str += '<option value="' + obj["id"] + '">' + obj["name"] + '</option>';
		});
		$("#category1").html(str);
		changeCategory();
		changeCategory2();
		//根据一级分类切换二级分类
		$("#category1").on("change", function(e) {
			changeCategory();
		});
		//根据二级分类切换三级分类
		$("#category2").on("change", function(e) {
			changeCategory2();
		});
	};
	//根据一级分类切换二级分类
	function changeCategory() {
			var id = $("#category1").val();
			var idIndex = -1;
			$.each(categoryData, function(index, obj) {
				if (obj["id"] == id) {
					idIndex = index;
					return false;
				}
			});
			var str = '';
			str += '<option value="' + idNotSelect + '" selected>' + levelTip2 + '</option>';
			if (idIndex != -1) {
				$.each(categoryData[idIndex]["child"], function(index, obj) {
					str += '<option value="' + obj["id"] + '">' + obj["name"] + '</option>';
				});
			}
			$("#category2").html(str);
			changeCategory2();
		}
		//根据二级分类切换三级分类

	function changeCategory2() {
		var superId = $("#category1").val();
		var id = $("#category2").val();
		var superIdIndex = -1;
		var idIndex = -1;
		var str = '';
		str += '<option value="' + idNotSelect + '" selected>' + levelTip3 + '</option>';
		$.each(categoryData, function(index, obj) {
			if (obj["id"] == superId) {
				superIdIndex = index;
				$.each(obj["child"], function(index2, obj2) {
					if (obj2["id"] == id) {
						if (obj2["child"]) {
							$.each(obj2["child"], function(index3, obj3) {
								str += '<option value="' + obj3["id"] + '">' + obj3["name"] + '</option>';
							});
						}
						return false;
					}
				});
				return false;
			}
		});

		//		if (superIdIndex != -1) {
		//			$.each(categoryData[superIdIndex]["child"], function(index, obj) {
		//				str += '<option value="' + obj["id"] + '">' + obj["name"] + '</option>';
		//			});
		//		}
		$("#category3").html(str);
	}

	//----------------------------------地图设置
	//点击"搜索"按钮
	$('#search').on('click', function(e) {
		fun_geocoder_getPoint(null);
	});

	//获取经度,纬度和地址
	var initAddress = $("#address").val();
	var longitudeValue = $("#longitude").val();
	var latitudeValue = $("#latitude").val();
	if (!longitudeValue) {
		longitudeValue = 113.401493;
		latitudeValue = 23.130024;
	}
	var map = new BMap.Map("mapContainer"); // 创建Map实例
	var point = new BMap.Point(longitudeValue, latitudeValue); // 创建点坐标   
	map.centerAndZoom(point, 12); // 初始化地图,设置中心点坐标和地图级别。
	//样式3
	var opts = {
		width: 350, // 信息窗口宽度 
		height: 50, // 信息窗口高度 
		title: "当前的位置是:" // 信息窗口标题 
	}
	var marker = new BMap.Marker(point); // 创建标注
	map.addOverlay(marker); // 将标注添加到地图中
	marker.enableDragging(); //可拖拽
	marker.setAnimation(BMAP_ANIMATION_BOUNCE);
	map.enableScrollWheelZoom();
	map.getPanorama(); //启用滚轮放大缩小
	var infoWindow = new BMap.InfoWindow("您可以拖动红点进行地理分析，也可以直接搜索后在拖动，或者直接用鼠标点击地图获取地理位置"); // 创建信息窗口对象 
	marker.openInfoWindow(infoWindow); //开启信息窗口
	marker.addEventListener("dragend", function() {
		var ps = marker.getPosition();
		$("#longitude").val(ps.lng.toString());
		$("#latitude").val(ps.lat.toString());
		marker.setAnimation();
		GetAddress(ps, this);
	});



	var options = {
		renderOptions: {
			map: map,
			panel: "mapContainer"
		}
	};
	var myLocalsearch = new BMap.LocalSearch(map, options);

	//创建地址解析的实例
	var myGeo = new BMap.Geocoder();
	//地址解析函数【搜索】
	function fun_geocoder_getPoint(addreVale) {
		var value_address_1;
		if (addreVale != null) {
			value_address_1 = addreVale;
		} else {
			value_address_1 = document.getElementById("address").value;
		}
		map.clearOverlays(); //清除覆盖物体
		myGeo.getPoint(value_address_1, function(pot) {
			if (pot) {
				map.centerAndZoom(pot, 15);
				var mar = new BMap.Marker(pot);
				mar.enableDragging();
				map.addOverlay(mar);
				mar.setAnimation(BMAP_ANIMATION_DROP);
				var p = mar.getPosition();
				$("#longitude").val(p.lng.toString());
				$("#latitude").val(p.lat.toString());
				GetAddressTxt(p, mar);
				mar.addEventListener("dragend", function() {
					var ps = mar.getPosition();
					$("#longitude").val(ps.lng.toString());
					$("#latitude").val(ps.lat.toString());
					GetAddress(ps, this);
				});
			}
		}, "全国");
	};



	//地图监听事件
	map.addEventListener("click", function(e) {
		var ps;
		var pt = e.point;
		myGeo.getLocation(pt, function(rs) {
			var addComp = rs.addressComponents;
			$("#address").val(addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber);
			map.clearOverlays();

			var markers = new BMap.Marker(pt); // 创建标注
			map.addOverlay(markers); // 将标注添加到地图中 
			markers.enableDragging(); //可拖拽
			markers.setAnimation(BMAP_ANIMATION_DROP);
			ps = markers.getPosition();
			$("#longitude").val(ps.lng.toString());
			$("#latitude").val(ps.lat.toString());
			GetAddress(ps, markers);

			markers.addEventListener("dragend", function() {
				ps = markers.getPosition();
				$("#longitude").val(ps.lng.toString());
				$("#latitude").val(ps.lat.toString());
				GetAddress(ps, this);
			});
		});
	});



	function GetAddress(lnglat, obj) {
		myGeo.getLocation(lnglat, function(rs) {
			var addComp = rs.addressComponents;
			$("#address").val(addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber);
			var infoWindowa = new BMap.InfoWindow($("#address").val(), opts); // 创建信息窗口对象
			obj.openInfoWindow(infoWindowa); //开启信息窗口
		});
	};

	function GetAddressTxt(lnglat, obj) {
		myGeo.getLocation(lnglat, function(rs) {
			var addComp = rs.addressComponents;
			//$("#address").val(addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber);
			var infoWindowa = new BMap.InfoWindow($("#address").val(), opts); // 创建信息窗口对象
			obj.openInfoWindow(infoWindowa); //开启信息窗口
		});
	};
	//建立一个自动完成的对象
	var ac = new BMap.Autocomplete({
		"input": "address",
		"location": map
	});
	ac.setInputValue(initAddress);
	ac.addEventListener("onhighlight", function(e) { //鼠标放在下拉列表上的事件
		var str = "";
		var _value = e.fromitem.value;

		var value = "";
		if (e.fromitem.index > -1) {
			value = _value.province + _value.city + _value.district + _value.street + _value.business;
		}
		str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

		value = "";
		if (e.toitem.index > -1) {
			_value = e.toitem.value;
			value = _value.province + _value.city + _value.district + _value.street + _value.business;
		}
		str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
	});

	var myValue;
	ac.addEventListener("onconfirm", function(e) { //鼠标点击下拉列表后的事件
		var _value = e.item.value;
		myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
		fun_geocoder_getPoint(myValue);
	});
});